package com.live.task;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.live.activity.R;
import com.live.adapter.LiveInfoReplaySA;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveInfoReplay extends AsyncTask<Bundle, Integer, String> {

	private LiveInfoReplaySA adapter;

	private List<Map<String, Object>> list;

	private List<Map<String, Object>> listTmp;

	private ListView listView;

	private View footerView;

	private Context context = null;

	private Dialog proDialog;

	private LinearLayout tabView;

	public LiveInfoReplay(Context context, List<Map<String, Object>> list, LiveInfoReplaySA adapter,
			LinearLayout tabView, ListView listView, View footerView) {
		this.context = context;
		this.adapter = adapter;
		this.list = list;
		this.tabView = tabView;
		this.listView = listView;
		this.footerView = footerView;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
		proDialog = new Dialog(context, R.style.progress_dialog);
		proDialog.setContentView(R.layout.live_progress_dialog);
		proDialog.show();
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());

		String uId = params[0].getString("uId");
		int page = params[0].getInt("page");
		String id = "0";

		String url = Constant.SITE_URL + "live_info_replay.php?locale=" + LiveTools.getLocaleLanguage();
		url += "&uId=" + uId;

		if (page == 0) {
			if (list.size() == 0) {
				url += "&id=" + id + "&path=0";
			} else {
				id = list.get(0).get("id").toString();
				url += "&id=" + id + "&path=-1";
			}
			listTmp = getInfoReplay(url);
			for (int i = 1; i <= listTmp.size(); i++) {
				list.add(0, listTmp.get(listTmp.size() - i));
			}
		} else {
			id = list.get(list.size() - 1).get("id").toString();
			url += "&id=" + id + "&path=1";
			listTmp = getInfoReplay(url);
			list.addAll(listTmp);
		}

		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());
	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
		proDialog.dismiss();

		if (listTmp.size() < Constant.PAGE_SIZE) {
			listView.removeFooterView(footerView);
		}
		
		adapter.notifyDataSetChanged();

		// 设置提醒数量
		TextView infoReplayCount = (TextView) tabView.findViewById(R.id.infoReplayCount);
		ImageView infoReplayCountImg = (ImageView) tabView.findViewById(R.id.infoReplayCountImg);

		if (list.size() == 0) {
			infoReplayCount.setVisibility(Constant.INVISIBLE);
			infoReplayCountImg.setVisibility(Constant.INVISIBLE);
		} else {
			infoReplayCount.setText(String.valueOf(list.size()));
			infoReplayCount.setVisibility(Constant.VISIBLE);
			infoReplayCountImg.setVisibility(Constant.VISIBLE);
		}
	}

	/**
	 * 记录观看比赛详细页的信息
	 * 
	 * @param url
	 * @return
	 */
	private List<Map<String, Object>> getInfoReplay(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						JSONArray news = new JSONObject(out).getJSONArray("results");
						for (int i = 0; i < news.length(); i++) {
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("id", news.getJSONObject(i).get("id"));
							map.put("replayId", news.getJSONObject(i).get("replayId"));
							map.put("matchId", news.getJSONObject(i).get("matchId"));
							map.put("uId", news.getJSONObject(i).get("uId"));
							map.put("userId", news.getJSONObject(i).get("userId"));
							map.put("atUserId", news.getJSONObject(i).get("atUserId"));
							map.put("userPic", news.getJSONObject(i).get("userPic"));
							map.put("userPicVer", news.getJSONObject(i).get("userPicVer"));
							map.put("userSex", news.getJSONObject(i).get("userSex"));
							map.put("userAge", news.getJSONObject(i).get("userAge"));
							map.put("userCity", news.getJSONObject(i).get("userCity"));
							map.put("userSign", news.getJSONObject(i).get("userSign"));
							map.put("content", news.getJSONObject(i).get("content"));
							map.put("topicContent", news.getJSONObject(i).get("topicContent"));
							map.put("updateDate", news.getJSONObject(i).get("updateDate"));
							data.add(map);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

}